﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace BuXiaChu.OrderDishes.BLL.StaticCache
{
    public class StaticCacheData : IStaticCache
    {
        private List<string> CacheKeyList
        {
            get;
            set;
        }

        public static IStaticCache Intance { get; private set; }
        static StaticCacheData()
        {
            Intance = new StaticCacheData();            
        }

        public StaticCacheData()
        {
            this.CacheKeyList = new List<string>();
        }

        public void Set(string key, object value, DateTime absoluteExpiration)
        {
            if (HttpRuntime.Cache.Get(key) == null)
            {
                CacheKeyList.Add(key);
                HttpRuntime.Cache.Add(key, value, null, absoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            else
            {
                HttpRuntime.Cache[key] = value;
            }
        }

        public void Set(string key, object value, TimeSpan slidingExpirations)
        {
            Set(key, value, DateTime.Now.Add(slidingExpirations));
        }

        public void Set(string key, object value)
        {
            if (HttpRuntime.Cache.Get(key) == null)
            {
                CacheKeyList.Add(key);
                HttpRuntime.Cache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            else
            {
                HttpRuntime.Cache[key] = value;
            }
        }

        public T Get<T>(string key)
        {
            if (HttpRuntime.Cache.Get(key) != null)
            {
                return (T)HttpRuntime.Cache.Get(key);
            }
            return default(T);
        }

        public bool TryGet<T>(string key, out T value)
        {
            value = Get<T>(key);
            if (value == null)
            {
                return false;
            }
            return true;
        }

        public void Delete(string key)
        {
            HttpRuntime.Cache.Remove(key);
        }

        public void DeleteAllCache()
        {
            foreach (var item in CacheKeyList)
            {
                Delete(item);
            }
        }
    }
}
